package com.yugao.fintech.antelope.system.listener;

import com.rabbitmq.client.Channel;
import com.yugao.fintech.antelope.base.model.constants.TenantCons;
import com.yugao.fintech.antelope.system.model.mq.TenantUpdateMQ;
import com.yugao.fintech.antelope.system.model.rqrs.tenant.TenantUpdateReq;
import com.yugao.fintech.antelope.system.service.SysTenantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
@RabbitListener(bindings = {
        @QueueBinding(
                value = @Queue(value = TenantUpdateMQ.QUEUE, durable = "true"),
                exchange = @Exchange(value = TenantUpdateMQ.EXCHANGE, type = ExchangeTypes.TOPIC))
})
public class TenantUpdateListener {
    @Autowired
    private SysTenantService tenantService;

    @RabbitHandler
    public void onMessage(@Payload String msg, Channel channel, Message message) {
        log.info("listener - tenant.update, msg: {}", msg);
        try {
            TenantUpdateMQ.MsgPayload msgPayload = TenantUpdateMQ.parse(msg, TenantUpdateMQ.MsgPayload.class);
            if (Objects.isNull(msgPayload.getTenantId())) {
                return;
            }
            if (TenantCons.SYSTEM_TENANT_ID.compareTo(msgPayload.getTenantId()) == 0) {
                return;
            }
            TenantUpdateReq req = new TenantUpdateReq();
            req.setId(msgPayload.getTenantId());
            req.setPackageId(msgPayload.getPackageId());
            req.setDomain(msgPayload.getDomain());

            if (Objects.nonNull(msgPayload.getPackageId()) && Objects.nonNull(msgPayload.getTenantId())) {
                tenantService.updateTenant(req);
                return;
            }
            log.error("update tenant params miss, params: {}", msg);
        } catch (Exception e) {
            log.error("error: ", e);
            throw e;
        }
    }
}
